package cn.im.thread;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * 多线程
 * @author Kevin
 */
public class ThreadDemo {

	public static void main(String[] args) {
		
		new MutliThread("thread1").start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("hello");
			}
		}).start();
	}


	@Test
	public void callable() throws ExecutionException, InterruptedException {
		//创建线程池
		ExecutorService service = Executors.newFixedThreadPool(1);
		//传入Callable实现同时启动线程
		Future submit = service.submit(new CallableThread());
		//获取线程内容的返回值，便于后续逻辑
		System.out.println(submit.get());
		//关闭线程池
		service.shutdown();
		//主线程
		System.out.println("这是main主线程：" + Thread.currentThread().getName());
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

/**
 * 实现Runnable接口，便于扩展
 * @author Kevin
 *
 */
class MyThread implements Runnable{
	private int ticket = 100;
	private String name;
	MyThread(String name) {
		this.name = name;
	}
	
	@Override
	public void run() {
		while (ticket > 0) {
			System.out.println(ticket--+"  is selled by :" + name);
		}
	}
}

/**
 * 继承Thread类
 * @author Kevin
 *
 */
class MutliThread extends Thread{
    private int ticket=100;//每个线程都拥有100张票
    MutliThread(String name){
        super(name);//调用父类带参数的构造方法
    }
    public void run(){
        while(ticket>0){
            System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
        }
    }
}


/**
 * 实现Callable接口
 */
class CallableThread implements Callable<String>{

	private int ticket=100;

	@Override
	public String call() throws Exception {
		while(ticket>0){
			System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
		}
		return "CallableThread: ticket sale out";
	}
}
